package service

import (
	"admin-system-go/model"
	"admin-system-go/model/do"
	"admin-system-go/model/dto"
	"admin-system-go/repository"
)

type MenuService interface {
	QueryMenu(dto dto.MenuQueryDTO) model.ResponseEntity
	CreateMenu(dto dto.MenuBaseDTO) model.ResponseEntity
	DelMenu(dto dto.MenuDelDTO) model.ResponseEntity
	UpdateMenu(updateDTO dto.MenuUpdateDTO) model.ResponseEntity
}

type menuServiceImpl struct{}

func (menuService menuServiceImpl) QueryMenu(queryDto dto.MenuQueryDTO) model.ResponseEntity {
	var menu do.Menu
	_ = repository.Copy(queryDto, &menu)
	var menus []do.Menu
	pageSize := queryDto.PageSize
	pageNo := queryDto.PageNo
	_ = repository.GetDb().Where(&menu).Limit(pageSize).Offset((pageNo - 1) * pageSize).Find(&menus)
	var result = make([]dto.MenuQueryDTO, len(menus))
	_ = repository.CopySlice(menus, result)
	var total int64
	if len(result) != 0 {
		_ = repository.GetDb().Model(&do.Menu{}).Where(&menu).Count(&total)
	}
	return model.PageEntityModel(result, &model.PageInfo{
		Total:    total,
		PageSize: pageSize,
		PageNo:   pageNo,
	})
}

func (menuService menuServiceImpl) CreateMenu(createDto dto.MenuBaseDTO) model.ResponseEntity {
	var menu do.Menu
	_ = repository.Copy(createDto, &menu)
	tx := repository.GetDb().Where(&do.Menu{Name: createDto.Name}).Find(&menu)
	if tx.RowsAffected > 0 {
		return model.FailEntityModel("菜单已经存在")
	}
	tx = repository.GetDb().Create(&menu)
	return model.BoolEntityModel(tx.RowsAffected == 1, tx.Error)
}

func (menuService menuServiceImpl) DelMenu(delDto dto.MenuDelDTO) model.ResponseEntity {
	tx := repository.GetDb().Delete(&do.Menu{}, delDto.MenuIds)
	return model.BoolEntityModel(tx.RowsAffected >= 1, tx.Error)
}

func (menuService menuServiceImpl) UpdateMenu(updateDTO dto.MenuUpdateDTO) model.ResponseEntity {
	var oldMenu do.Menu = do.Menu{Model: model.Model{Id: updateDTO.Id}}
	tx := repository.GetDb().Model(&oldMenu).Find(&oldMenu)
	if tx.RowsAffected == 0 {
		return model.FailEntityModel("菜单不存在")
	}
	_ = repository.Copy(updateDTO, &oldMenu)
	tx = repository.GetDb().Model(&oldMenu).Save(&oldMenu)
	if tx.Error == nil {
		return model.SuccessEntityModel(true)
	} else {
		return model.FailEntityModel("更新失败")
	}
}
